<?php
/*
 * @Description: file content
 * @FilePath: \auxface_certificate\app\certificate\controller\admin\v1\machineRisk\Index.php
 */

declare(strict_types=1);

namespace app\certificate\controller\admin\v1\machineRisk;

use libs\ALiOss;
use think\facade\Db;
use think\Request;
use ZipArchive;

class Index
{
  /**
   * @Description: 查看列表
   */
  public function getList(Request $request)
  {
    $data = $request->data;

    $searchWhere = [
      ['rt.projectCode', '=', $request->prjCode],
    ];

    //状态,待审核-0,使用中-1，已过期-2
    if (!empty($data['status']) || (isset($data['status']) && $data['status'] == 0)) {
      if ($data['status'] == 2) {
        array_push($searchWhere, ['r.expiredTime', '<', date('Y-m-d H:i:s')]);
      } else {
        array_push($searchWhere, ['r.status', '=', $data['status']]);
        array_push($searchWhere, ['r.expiredTime', '>', date('Y-m-d H:i:s')]);
      }
    }
    if (!empty($data['workerName'])) array_push($searchWhere, ['wi.workerName', 'like', "%{$data['workerName']}%"]);
    if (!empty($data['typeUuid'])) array_push($searchWhere, ['r.typeUuid', '=', $data['typeUuid']]);
    if (isset($request->authWhere['corpCode'])) array_push($searchWhere, ['rt.corpCode', '=', $request->authWhere['corpCode']]);
    if (!empty($data['machineUuid'])) array_push($searchWhere, ['r.machineUuid', '=', $data['machineUuid']]);

    $list = DB::table('certificate_machineRisk')
      ->alias('r')
      ->join('certification_projectWorker wi', 'wi.wxappUserUuid = r.wxappUserUuid', 'left')
      ->join('certificate_machineRiskType rt', 'rt.uuid = r.typeUuid')
      ->join('certificate_area a', 'a.uuid = r.areaUuid', 'left')
      ->where($searchWhere)
      ->page((int)$data['page'], (int)$data['limit'])
      ->field(['rt.name as typeName', 'wi.workerName', 'r.inDate', 'r.status', 'r.uuid', 'r.expiredTime', 'a.name as areaName'])
      ->order('r.id desc')
      ->distinct(true)
      ->select()->toArray();

    foreach ($list as &$value) {
      if (strtotime($value['expiredTime']) < time()) {
        $value['status'] = '2'; //已过期
      }
    }

    $count = DB::table('certificate_machineRisk')
      ->alias('r')
      ->join('certification_projectWorker wi', 'wi.wxappUserUuid = r.wxappUserUuid')
      ->join('certificate_machineRiskType rt', 'rt.uuid = r.typeUuid')
      ->join('certificate_area a', 'a.uuid = r.areaUuid', 'left')
      ->where($searchWhere)
      ->distinct(true)
      ->count();

    $data  =  compact('list', 'count');
    return result(SUCCESS, $data, '');
  }
  /**
   * @Description: 
   */
  public function getDetail(Request $request)
  {
    $data = $request->data;

    $data = DB::table('certificate_machineRisk')
      ->alias('r')
      ->join('certification_projectWorker wi', 'wi.wxappUserUuid = r.wxappUserUuid', 'left')
      ->join('certificate_machineRiskType rt', 'rt.uuid = r.typeUuid')
      ->join('certificate_area a', 'a.uuid = r.areaUuid', 'left')
      ->where('r.uuid', $data['uuid'])
      ->field(['rt.name as typeName', 'wi.workerName', 'r.inDate', 'r.status', 'r.uuid', 'r.expiredTime', 'a.name as areaName'])
      ->find();
    if (!$data) return result(FAIL, [], '数据有误请重试');

    //已過期
    if (strtotime($data['expiredTime']) < time()) $data['status'] = '2';

    $riskRecord = DB::table('certificate_flowForm')
      ->alias('ff')
      ->join('certificate_machineRiskRecord r', 'r.flowFormUuid = ff.uuid')
      ->where('r.riskUuid', $data['uuid'])
      ->order('ff.flowOrder asc')
      ->field('ff.uuid,ff.name,ff.subtitle,r.formData')
      ->group('ff.uuid')
      ->select()->toArray();
    foreach ($riskRecord as $key => $item) {
      $riskRecord[$key]['formData'] = json_decode(html_entity_decode($item['formData']), true);
    }
    $data['recordList'] = $riskRecord;

    return result(SUCCESS, $data, '');
  }
  /**
   * @Description: 
   * @param {Request} $request
   */
  public function getSubList(Request $request)
  {
    $data  = $request->data;
    $limit =  $data['limit'];
    $page =  $data['page'];

    $searchWhere = [
      ['sf.riskUuid', '=', $data['uuid']],
    ];

    //状态,待审核-0,使用中-1，已过期-2
    if (!empty($data['status']) || (isset($data['status']) && $data['status'] == 0)) {
      if ($data['status'] == 2) {
        array_push($searchWhere, ['sf.expiredTime', '<', date('Y-m-d H:i:s')]);
      } else {
        array_push($searchWhere, ['sf.status', '=', $data['status']]);
        array_push($searchWhere, ['sf.expiredTime', '>', date('Y-m-d H:i:s')]);
      }
    }

    if (!empty($data['name'])) array_push($searchWhere, ['sf.name', 'like', $data['name'] . "%"]);
    if (!empty($data['workerName'])) array_push($searchWhere, ['wi.workerName', 'like', "%{$data['workerName']}%"]);
    if (!empty($data['typeUuid'])) array_push($searchWhere, ['sf.subFormUuid', '=', $data['typeUuid']]);

    $list = DB::table('certificate_machineRiskSubform')->alias('sf')
      ->join('certificate_subform s', 's.uuid=sf.subFormUuid')
      ->join('certification_projectWorker wi', 'wi.wxappUserUuid = sf.wxappUserUuid', 'left')
      ->where($searchWhere)
      ->field(['wi.workerName', 's.name', 'sf.inDate', 'sf.uuid', 'sf.status', 'sf.expiredTime'])
      ->order('sf.id desc')
      ->page((int)$page, (int)$limit)
      ->select();

    $count = DB::table('certificate_machineRiskSubform')->alias('sf')
      ->join('certificate_subform s', 's.uuid=sf.subFormUuid')
      ->join('certification_projectWorker wi', 'wi.wxappUserUuid = sf.wxappUserUuid', 'left')
      ->where($searchWhere)
      ->count();

    $data = compact('list', 'count');

    return result(SUCCESS, $data);
  }

  /**
   * @Description: 获取数据
   * @param {Request} $request
   */
  public function getSubDetail(Request $request)
  {
    $data = $request->data;
    $uuid = $data['uuid'];

    $data = DB::table('certificate_machineRiskSubform')->alias('sf')
      ->join('certificate_subform s', 's.uuid=sf.subFormUuid')
      ->join('certification_projectWorker wi', 'wi.wxappUserUuid = sf.wxappUserUuid', 'left')
      ->where('sf.uuid', $uuid)
      ->field(['wi.workerName', 's.name', 'sf.inDate', 'sf.uuid', 'sf.status', 'sf.expiredTime'])
      ->find();
    $record = DB::table('certificate_flowForm')
      ->alias('ff')
      ->join('certificate_machineRiskSubFormRecord r', 'r.flowFormUuid = ff.uuid')
      ->where('r.subFormUuid', $uuid)
      ->order('ff.flowOrder asc')
      ->field('ff.uuid,ff.name,r.formData')
      ->group('ff.uuid')
      ->select()->toArray();
    foreach ($record as $key => $item) {
      $record[$key]['formData'] = json_decode(html_entity_decode($item['formData']), true);
    }
    $data['recordList'] = $record;

    return result(SUCCESS, $data, '');
  }

  public function html2pdf(Request $request)
  {
    $data = $request->data;
    $uuid = $data['uuid'];
    $where = [
      'isDelete' => 0,
      'uuid' => $uuid
    ];
    //查看提交记录
    $flowUuid = DB::table('certificate_machineRisk')
      // ->alias('r')
      // ->leftJoin('certificate_machineRiskType rt', 'r.typeUuid = rt.uuid')
      // ->leftJoin('certificate_area a', 'a.uuid=r.areaUuid')
      ->where($where)
      // ->order('r.id DESC')
      // ->field(['r.status'])
      // ->findOrEmpty();
    ->value('flowUuid');
    if (!$flowUuid) return result(FAIL, '', '獲取失敗，請返回重試');
    // if ($riskStatus != 1)  return result(FAIL, '', '许可证未审核完成');

    $template = DB::table('certificate_flow')->where('uuid',$flowUuid)->value('exportTemplate');
    // $riskRecord = DB::table('certificate_flowForm')
    //   ->alias('ff')
    //   ->join('certificate_machineRiskRecord r', 'r.flowFormUuid = ff.uuid')
    //   ->where('r.riskUuid', $uuid)
    //   ->order('ff.showOrder asc, ff.flowOrder asc,r.id asc')
    //   ->field('r.riskUuid,r.uuid,ff.uuid as formUuids,ff.name,ff.subtitle,r.formData,ff.exportTemplate')
    //   ->group('r.uuid')
    //   ->select()->toArray();
      
    // if (!$data) return result(FAIL, '', '没有提交记录');
    // $newArr = [];
    // foreach ($riskRecord as $key => $item) {
    //   if (empty($item['exportTemplate'])) return result(FAIL, '', '请设置导出模板');
    //   $newArr[$item['exportTemplate']][] = $item;
    // }
    // foreach ($newArr as $key => $value) {
      // $formUuids = array_column($value, 'formUuids');
      // $formUuids = implode(',', $formUuids);
      // $templateName = $key;
      $domain = request()->domain();
      $url = $domain . "/api/certificate/admin/v1/machineRisk/index/pdf?uuid={$uuid}&formUuid={$flowUuid}&templateName={$template}";
      dd($url);
      $path2 = 'uploads/' . time() . '.pdf';
      $path = root_path() . '/public/' . $path2;
      // 获取文件的目录路径
      $dir = dirname($path);
      // 判断目录是否存在
      if (!is_dir($dir)) {
        // 如果目录不存在，则创建目录
        if (!mkdir($dir, 0777, true)) {
          // 如果创建失败，可以抛出错误或处理异常
          return result(FAIL, '', '创建目录失败');
        }
      }
      $token = $_SERVER["HTTP_AUTHORIZATION"];
      $userUuid = $_SERVER["HTTP_UUID"];

      // 执行 wkhtmltopdf 命令
      $command = "wkhtmltopdf " .
        "--custom-header 'Authorization' {$token} " .
        "--custom-header 'uuid' {$userUuid} " .
        "--custom-header 'corpCode' {$request->corpCode} " .
        "--custom-header 'puuid' {$request->prjCode} " .
        "{$url} {$path}";
      exec($command . ' 2>&1', $output, $result_code);
      // $files[] = $path;
    // }
// 
    $path2 = 'uploads/' . time() . '.zip';
    $path = root_path() . '/public/' . $path2;

    //多个文件压缩到zip文件
    // $this->addZip($path, $files);
    // if (file_exists($path) == false) {
    //   return result(FAIL, '', '导出pdf失败');
    // }
    $exp = explode('.', $path2);
    $oss = new ALiOss($exp[0], $exp[1]);
    $ossPath = $oss->upload($path2);
    @unlink($path);
    return result(SUCCESS, ['path' => $ossPath], '导出路径');
  }

  public function pdf(Request $request)
  {
    $data = $request->data;
    $uuid = $data['uuid'];
    $templateName = $data['templateName'];
    $formUuids = explode(',', $data['formUuids']);
    $where = [
      'r.isDelete' => 0,
      'r.uuid' => $uuid,
    ];
    //查看提交记录
    $riskData = DB::table('certificate_machineRisk')
      ->alias('r')
      ->leftJoin('certificate_machineRiskType rt', 'r.typeUuid = rt.uuid')
      ->leftJoin('certificate_area a', 'a.uuid=r.areaUuid')
      ->where($where)
      ->order('r.id DESC')
      ->field(['r.status'])
      ->findOrEmpty();
    if (!$riskData) return result(FAIL, '', '獲取失敗，請返回重試');
    if ($riskData['status'] != 1)  return result(FAIL, '', '许可证未审核完成');

    $record = DB::table('certificate_flowForm')
      ->alias('ff')
      ->join('certificate_machineRiskRecord r', 'r.flowFormUuid = ff.uuid')
      ->where('r.riskUuid', $uuid)
      ->whereIn('ff.uuid', $formUuids)
      ->order('ff.showOrder asc, ff.flowOrder asc,r.id asc')
      ->field('r.riskUuid,r.uuid,ff.name,ff.subtitle,r.formData,ff.exportTemplate')
      ->group('r.uuid')
      ->select()->toArray();
    if (!$record) return result(FAIL, '', '没有提交记录');
    $formData = [];
    $subForm = [];
    foreach ($record as &$item) {
      if (empty($item['exportTemplate'])) return result(FAIL, '', '请设置导出模板');
      $item['formData'] = json_decode(html_entity_decode($item['formData']), true);
      $item['formData'] = array_column($item['formData'], 'defaultValue', 'label');
      foreach ($item['formData'] as $key2 => $item2) {
        $key3 = preg_replace('/[（）]/', '', $key2);
        $item['formData'][$key3] = $item2;
        unset($item['formData'][$key2]);
      }

      //关联附表
      $subForm = Db::table('certificate_machineRiskSubForm')->where('sf')
        ->join('certificate_subForm s', 's.uuid=sf.subFormUuid')
        ->group('s.uuid')
        ->column('s.name');
      $formData = array_merge($formData, $item['formData']);
    }
    $templateName = app_path() . "/view/admin/v1/machineRisk/index/{$templateName}";
    return view($templateName, ['data' => $formData]);
  }

  /**
   * zip文件打包
   */
  public function addZip($zipname, $files)
  {
    $zip = new \ZipArchive();
    $res = $zip->open($zipname, \ZipArchive::CREATE);
    if ($res === TRUE) {
      foreach ($files as $file) {
        //这里直接用原文件的名字进行打包，也可以直接命名，需要注意如果文件名字一样会导致后面文件覆盖前面的文件，所以建议重新命名
        $new_filename = substr($file, strrpos($file, '/') + 1);
        $zip->addFile($file, $new_filename);
      }
    }
    //关闭文件
    $zip->close();
    //删除旧文件
    foreach ($files as $file) {
      @unlink($file);
    }
  }

  /**
   * 目录不存在则创建
   */
  function mkdir_chmod($path, $mode = 0777)
  {
    if (is_dir($path)) {
      return true;
    }
    $result = mkdir($path, $mode, true);
    return $result;
  }
}
